<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>欢迎光临</title>
  <style>
    body {
      text-align: center;
    }

    .login {
      margin-top: 10px;
    }

    .content {
      background: #00fff31f;
      width: 60%;
      min-height: 200px;
      margin: 20px auto;
    }

    table {
      margin: 20px auto 0;
    }
  </style>
</head>

<body>
  <h1>欢迎来到 spring boot</h1>
  <div>
    <div>用户名：<input type="text" id="userName" /></div>
    <div>密&emsp;码：<input type="text" id="passWord" /></div>
    <button class="login" onclick="login()">登录</button>
    <div class="content">
      <button onclick="setData()">新增数据</button>
      <button onclick="getData()">获取列表数据</button>
      <div>
        <input type="file" id="file">
        <button onclick="uploadFile()">上传文件</button>
        <div id="fileList"></div>
      </div>
      <table border>
        <thead>
          <tr>
            <th>用户名</th>
            <th>密码</th>
            <th>是否管理员</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="table"></tbody>
      </table>
    </div>
  </div>

  <script>
    function callback(res) {
      if (res.code !== '0') {
        alert(JSON.stringify(res));
        return false;
      }
      return true;
    }
    const myFetch = {
      get: (url) => {
        return fetch("/icbc" + url).then((res) => res.json()).then(res => callback(res) ? res : null);
      },
      post: (url, json) => {
        url = "/icbc" + url;
        return fetch(url, {
          credentials: 'include',
          method: "POST",
          headers: {
            "Content-Type": "application/json", // 根据实际情况设置请求头
          },
          body: JSON.stringify(json), // 将数据转换为 JSON 字符串
        }).then((res) => res.json()).then(res => callback(res) ? res : null);
      },
      postFile: (url, data) => {
        url = "/icbc" + url;
        return fetch(url, {
          credentials: 'include',
          method: "POST",
          body: data, // 将数据转换为 JSON 字符串
        }).then((res) => res.json()).then(res => callback(res) ? res : null);
      },
    };
    const file = document.getElementById('file');
    const fileList = document.getElementById('fileList');
    const table = document.getElementById('table');

    function login() {
      const userName = document.querySelector("#userName").value;
      const passWord = document.querySelector("#passWord").value;

      myFetch
        .post("/login", { userName, passWord, name: userName })
        .then((res) => {
          res && alert(JSON.stringify(res));
        });
    }

    function getData() {
      myFetch
        .get("/getAllUser")
        .then((res) => {
          if (res && res.code === '0') {
            let str = '';
            res.res.forEach(item => {
              str += `<tr>
                <td>${item.userName}</td>
                <td>${item.passWord}</td>
                <td>${item.isAdmin}</td>
                <td>${item.createdAt}</td>
                <td><button class="modify" data-id=${item.id}>修改</button><button class="delete" data-id=${item.id}>删除</button></td>
                </tr>`
            });
            table.innerHTML = str;
          }
        });
    }
    function setData() {
      const userName = document.querySelector("#userName").value;
      const passWord = document.querySelector("#passWord").value;

      myFetch
        .post("/setData", { userName, passWord, name: userName })
        .then((res) => {
          if(res && res.code === "0") {
            getData();
            alert("新增成功");
          }
        });
    }

    // 删除 和 修改
    table.addEventListener('click', (e)=> {
      const {dataset, classList} = e.target;
      if(classList.contains("delete")) {
        myFetch.post('/deleteUser', {userId: dataset.id}).then(res => {
          if(res && res.code === "0") {
            getData();
            alert("删除成功");
          }
        })
      } else if(classList.contains("modify")) {

      }
    })

    function uploadFile() {
      const data = file.files[0];
      if (data) {
        const fd = new FormData();
        fd.append("file", data);
        myFetch.postFile('/upload', fd).then(res => {
          if (res && res.code === '0') {
            const image = document.createElement('img');
            image.src = res.url;
            image.height = 100;
            fileList.appendChild(image);
            alert(JSON.stringify(res));
          }
        })
      }
    }
  </script>
</body>

</html>